'use client'

import React, { useEffect, useState } from 'react'
import {
    Card,
    Progress,
    Typography,
    Space,
    Tag,
    Timeline,
    Alert,
    Statistic,
    Row,
    Col,
    Button,
    Descriptions,
    List,
    Badge,
    Tooltip
} from 'antd'
import {
    ClockCircleOutlined,
    CheckCircleOutlined,
    ExclamationCircleOutlined,
    LoadingOutlined,
    StopOutlined,
    PlayCircleOutlined,
    InfoCircleOutlined,
    WarningOutlined,
    BugOutlined
} from '@ant-design/icons'
import { TaskStatusInfo, Task } from '@/types/task'
import { useTaskStore } from '@/stores/taskStore'

const { Title, Text, Paragraph } = Typography

interface TaskStatusDisplayProps {
    task: Task
    onCancel?: () => void
    onRetry?: () => void
}

// TaskLog接口已在taskStore中定义

export const TaskStatusDisplay: React.FC<TaskStatusDisplayProps> = ({
    task,
    onCancel,
    onRetry
}) => {
    const {
        taskStatuses,
        executionContexts,
        errors,
        getTaskLogs
    } = useTaskStore()

    const [currentTime, setCurrentTime] = useState(new Date())

    const taskStatus = taskStatuses[task.id]
    const executionContext = executionContexts[task.id]
    const taskError = errors[task.id]
    const taskLogs = getTaskLogs(task.id)

    // 更新当前时间用于计算执行时间
    useEffect(() => {
        const timer = setInterval(() => {
            setCurrentTime(new Date())
        }, 1000)

        return () => clearInterval(timer)
    }, [])

    const getStatusIcon = (status: string) => {
        switch (status) {
            case 'running':
                return <LoadingOutlined spin className="text-blue-500" />
            case 'completed':
                return <CheckCircleOutlined className="text-green-500" />
            case 'error':
                return <ExclamationCircleOutlined className="text-red-500" />
            case 'cancelled':
                return <StopOutlined className="text-gray-500" />
            case 'pending':
                return <ClockCircleOutlined className="text-orange-500" />
            default:
                return <InfoCircleOutlined className="text-gray-400" />
        }
    }

    const getStatusColor = (status: string) => {
        switch (status) {
            case 'running':
                return 'processing'
            case 'completed':
                return 'success'
            case 'error':
                return 'error'
            case 'cancelled':
                return 'default'
            case 'pending':
                return 'warning'
            default:
                return 'default'
        }
    }

    const getStatusText = (status: string) => {
        switch (status) {
            case 'running':
                return '运行中'
            case 'completed':
                return '已完成'
            case 'error':
                return '执行失败'
            case 'cancelled':
                return '已取消'
            case 'pending':
                return '等待中'
            case 'idle':
                return '就绪'
            default:
                return '未知状态'
        }
    }

    const calculateExecutionTime = () => {
        if (!executionContext?.startTime) return 0
        return Math.floor((currentTime.getTime() - executionContext.startTime.getTime()) / 1000)
    }

    const formatDuration = (seconds: number) => {
        const hours = Math.floor(seconds / 3600)
        const minutes = Math.floor((seconds % 3600) / 60)
        const secs = seconds % 60

        if (hours > 0) {
            return `${hours}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
        }
        return `${minutes}:${secs.toString().padStart(2, '0')}`
    }

    const getLogIcon = (level: string) => {
        switch (level) {
            case 'error':
                return <ExclamationCircleOutlined className="text-red-500" />
            case 'warning':
                return <WarningOutlined className="text-orange-500" />
            case 'debug':
                return <BugOutlined className="text-purple-500" />
            default:
                return <InfoCircleOutlined className="text-blue-500" />
        }
    }

    const renderProgressSection = () => {
        if (!taskStatus && !executionContext) {
            return (
                <Alert
                    message="任务未开始"
                    description="任务尚未启动，请配置参数后开始执行。"
                    type="info"
                    showIcon
                />
            )
        }

        const progress = executionContext?.progress || 0
        const currentStep = executionContext?.currentStep || '准备中'
        const totalSteps = executionContext?.totalSteps || 1

        return (
            <Space direction="vertical" size="middle" className="w-full">
                <div className="flex items-center justify-between">
                    <Title level={5} className="mb-0">执行进度</Title>
                    <Tag
                        color={getStatusColor(task.status)}
                        icon={getStatusIcon(task.status)}
                    >
                        {getStatusText(task.status)}
                    </Tag>
                </div>

                <Progress
                    percent={Math.round(progress)}
                    status={
                        task.status === 'error' ? 'exception' :
                            task.status === 'running' ? 'active' :
                                task.status === 'completed' ? 'success' : 'normal'
                    }
                    strokeColor={{
                        '0%': '#108ee9',
                        '100%': '#87d068',
                    }}
                />

                <Row gutter={16}>
                    <Col span={8}>
                        <Statistic
                            title="当前步骤"
                            value={`${Math.floor(progress / 100 * totalSteps)}/${totalSteps}`}
                        />
                    </Col>
                    <Col span={8}>
                        <Statistic
                            title="执行时间"
                            value={formatDuration(calculateExecutionTime())}
                        />
                    </Col>
                    <Col span={8}>
                        <Statistic
                            title="预计剩余"
                            value={
                                progress > 0 && task.status === 'running'
                                    ? formatDuration(Math.floor(calculateExecutionTime() * (100 - progress) / progress))
                                    : '--'
                            }
                        />
                    </Col>
                </Row>

                <div className="bg-gray-50 p-3 rounded">
                    <Text strong>当前步骤: </Text>
                    <Text>{currentStep}</Text>
                </div>

                {task.status === 'running' && onCancel && (
                    <Button
                        type="default"
                        danger
                        icon={<StopOutlined />}
                        onClick={onCancel}
                    >
                        取消任务
                    </Button>
                )}

                {task.status === 'error' && onRetry && (
                    <Button
                        type="primary"
                        icon={<PlayCircleOutlined />}
                        onClick={onRetry}
                    >
                        重试任务
                    </Button>
                )}
            </Space>
        )
    }

    const renderErrorSection = () => {
        if (!taskError) return null

        return (
            <Alert
                message="任务执行错误"
                description={
                    <Space direction="vertical" size="small" className="w-full">
                        <Text>{taskError.message}</Text>
                        {taskError.code && (
                            <Text code>错误代码: {taskError.code}</Text>
                        )}
                        {taskError.retryCount > 0 && (
                            <Text type="secondary">
                                重试次数: {taskError.retryCount}
                            </Text>
                        )}
                        {taskError.details && (
                            <details>
                                <summary className="cursor-pointer text-blue-600">
                                    查看详细信息
                                </summary>
                                <pre className="mt-2 text-xs bg-gray-100 p-2 rounded overflow-auto">
                                    {JSON.stringify(taskError.details, null, 2)}
                                </pre>
                            </details>
                        )}
                    </Space>
                }
                type="error"
                showIcon
                className="mb-4"
            />
        )
    }

    const renderTaskInfo = () => (
        <Descriptions column={1} size="small">
            <Descriptions.Item label="任务ID">{task.id}</Descriptions.Item>
            <Descriptions.Item label="任务类型">
                {task.type === 'detection' ? '病灶检测' :
                    task.type === 'classification' ? '影像分类' : '图像分割'}
            </Descriptions.Item>
            <Descriptions.Item label="创建时间">
                {new Date(task.createdAt).toLocaleString()}
            </Descriptions.Item>
            {task.estimatedDuration && (
                <Descriptions.Item label="预估时长">
                    {formatDuration(task.estimatedDuration)}
                </Descriptions.Item>
            )}
            {task.priority !== undefined && (
                <Descriptions.Item label="优先级">
                    <Tag color={
                        task.priority >= 3 ? 'red' :
                            task.priority >= 2 ? 'orange' :
                                task.priority >= 1 ? 'blue' : 'default'
                    }>
                        {task.priority >= 3 ? '紧急' :
                            task.priority >= 2 ? '高' :
                                task.priority >= 1 ? '普通' : '低'}
                    </Tag>
                </Descriptions.Item>
            )}
        </Descriptions>
    )

    const renderExecutionLogs = () => {
        if (!taskLogs || taskLogs.length === 0) {
            return (
                <div className="text-center py-8 text-gray-500">
                    <InfoCircleOutlined className="text-2xl mb-2" />
                    <div>暂无执行日志</div>
                </div>
            )
        }

        return (
            <List
                size="small"
                dataSource={taskLogs.slice(-10)} // 只显示最近10条日志
                renderItem={(log) => (
                    <List.Item>
                        <div className="w-full">
                            <div className="flex items-center justify-between mb-1">
                                <Space>
                                    {getLogIcon(log.level)}
                                    <Text strong className={
                                        log.level === 'error' ? 'text-red-600' :
                                            log.level === 'warning' ? 'text-orange-600' :
                                                log.level === 'debug' ? 'text-purple-600' :
                                                    'text-blue-600'
                                    }>
                                        {log.level.toUpperCase()}
                                    </Text>
                                </Space>
                                <Text type="secondary" className="text-xs">
                                    {log.timestamp.toLocaleTimeString()}
                                </Text>
                            </div>
                            <Paragraph className="mb-0 text-sm">
                                {log.message}
                            </Paragraph>
                            {log.details && (
                                <details className="mt-1">
                                    <summary className="cursor-pointer text-xs text-gray-500">
                                        详细信息
                                    </summary>
                                    <pre className="text-xs bg-gray-50 p-2 mt-1 rounded overflow-auto">
                                        {JSON.stringify(log.details, null, 2)}
                                    </pre>
                                </details>
                            )}
                        </div>
                    </List.Item>
                )}
            />
        )
    }

    return (
        <Space direction="vertical" size="large" className="w-full">
            {/* 任务基本信息 */}
            <Card title="任务信息" size="small">
                {renderTaskInfo()}
            </Card>

            {/* 错误信息 */}
            {renderErrorSection()}

            {/* 执行进度 */}
            <Card title="执行状态" size="small">
                {renderProgressSection()}
            </Card>

            {/* 执行日志 */}
            <Card
                title="执行日志"
                size="small"
                extra={
                    taskLogs.length > 10 && (
                        <Tooltip title="仅显示最近10条日志">
                            <Badge count={taskLogs.length} showZero>
                                <InfoCircleOutlined />
                            </Badge>
                        </Tooltip>
                    )
                }
            >
                {renderExecutionLogs()}
            </Card>
        </Space>
    )
}

export default TaskStatusDisplay